package com.genesis.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.genesis.mall.common.Result;
import com.genesis.mall.dto.PageDto;
import com.genesis.mall.dto.RoleMenuDto;
import com.genesis.mall.dto.RoleResourceDto;
import com.genesis.mall.entity.*;
import com.genesis.mall.service.*;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台用户角色表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-08-01
 */
@Slf4j
@RestController
@RequestMapping("/role")
public class UmsRoleController {
    @Autowired
    private IUmsRoleService roleService;

    @Autowired
    private IUmsRoleMenuRelationService umsRoleMenuRelationService;

    @Autowired
    private IUmsMenuService umsMenuService;

    @Autowired
    private IUmsRoleResourceRelationService roleResourceRelationService;

    @Autowired
    private IUmsResourceService resourceService;

    /**
     * 获得所有角色
     *
     * @return
     */
    @GetMapping("/listAll")
    public Result<List<UmsRole>> listAll() {
        LambdaQueryWrapper<UmsRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRole::getStatus, 1);
        List<UmsRole> umsRoles = roleService.list(lqw);
        return Result.success(umsRoles);
    }

    /**
     * 根据角色名称和分页获取角色列表
     *
     * @param pageDto
     * @return
     */
    @GetMapping("/list")
    public Result<PageDto<UmsRole>> list(PageDto<UmsRole> pageDto) {
        Page<UmsRole> page = new Page<>(pageDto.getPageNum(), pageDto.getPageSize());
        LambdaQueryWrapper<UmsRole> lqw = new LambdaQueryWrapper<>();
        lqw.like(pageDto.getKeyword() != null, UmsRole::getName, pageDto.getKeyword());
        roleService.page(page, lqw);
        //将数据封装到pageDto
        pageDto.setTotal((int) page.getTotal());
        pageDto.setTotalPage((int) page.getPages());
        pageDto.setList(page.getRecords());
        return Result.success(pageDto);
    }

    /**
     * 添加角色
     *
     * @param umsRole
     * @return
     */
    @PostMapping("/create")
    public Result<String> create(@RequestBody UmsRole umsRole) {
        if (StringUtils.isEmpty(umsRole.getName())) {
            return Result.error("角色名不能为空");
        }
        //判断角色名是否已存在
        LambdaQueryWrapper<UmsRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRole::getName, umsRole);
        List<UmsRole> umsRoles = roleService.list(lqw);
        if (umsRoles == null) {
            return Result.error("角色已存在");
        }
        //将角色添加到数据库中
        umsRole.setCreateTime(LocalDateTime.now());
        roleService.save(umsRole);
        return Result.success();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    public Result<String> delete(String ids) {
        roleService.removeById(ids);
        return Result.success();
    }

    /**
     * 修改状态
     *
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/updateStatus/{id}")
    public Result<String> updateStatus(@PathVariable Long id, Integer status) {
        //通过id查找角色
        UmsRole umsRole = roleService.getById(id);
        //修改umsRole的状态
        umsRole.setStatus(status);
        roleService.updateById(umsRole);
        return Result.success();
    }

    /**
     * 修改角色
     */
    @PostMapping("/update/{id}")
    public Result update(@PathVariable Long id, @RequestBody UmsRole umsRole) {
        roleService.updateById(umsRole);
        return Result.success();
    }

    /**
     * 获得角色相关菜单
     */
    @GetMapping("/listMenu/{id}")
    public Result<List<UmsMenu>> listMenu(@PathVariable Long id) {
        LambdaQueryWrapper<UmsRoleMenuRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRoleMenuRelation::getRoleId, id);
        List<UmsRoleMenuRelation> umsRoleMenuRelations = umsRoleMenuRelationService.list(lqw);
        //获得角色的菜单列表
        List<Long> menuIds = umsRoleMenuRelations.stream().map(UmsRoleMenuRelation::getMenuId).collect(Collectors.toList());
        List<UmsMenu> umsMenus = menuIds.stream().map(menuId -> {
            return umsMenuService.getById(menuId);
        }).collect(Collectors.toList());
        return Result.success(umsMenus);
    }

    /**
     * 给角色分配菜单
     */
    @PostMapping("/allocMenu")
    public Result<String> allocMenu(RoleMenuDto roleMenuDto) {
        Long roleId = roleMenuDto.getRoleId();
        List<Long> menuIds = roleMenuDto.getMenuIds();
        //删除改角色之前分配的菜单
        LambdaQueryWrapper<UmsRoleMenuRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRoleMenuRelation::getRoleId, roleId);
        umsRoleMenuRelationService.remove(lqw);
        //向角色菜单表中添加数据
        List<UmsRoleMenuRelation> roleMenuRelations = menuIds.stream().map(menuId -> {
            UmsRoleMenuRelation roleMenuRelation = new UmsRoleMenuRelation();
            roleMenuRelation.setRoleId(roleId);
            roleMenuRelation.setMenuId(menuId);
            return roleMenuRelation;
        }).collect(Collectors.toList());
        //将数据保存
        umsRoleMenuRelationService.saveBatch(roleMenuRelations);
        return Result.success();
    }

    /**
     * 获取角色资源
     */
    @GetMapping("/listResource/{id}")
    public Result<List<UmsResource>> listResource(@PathVariable Long id) {
        //通过id查询相关资源id
        LambdaQueryWrapper<UmsRoleResourceRelation> roleResourceLqw = new LambdaQueryWrapper<>();
        roleResourceLqw.eq(UmsRoleResourceRelation::getRoleId, id);
        List<UmsRoleResourceRelation> roleResourceRelations = roleResourceRelationService.list(roleResourceLqw);
        List<Long> resourceIds = roleResourceRelations.stream().map(UmsRoleResourceRelation::getResourceId).collect(Collectors.toList());
        //根据资源id查找相关的资源
        List<UmsResource> umsResources = resourceIds.stream().map(resourceId -> {
            return resourceService.getById(resourceId);
        }).collect(Collectors.toList());
        return Result.success(umsResources);
    }

    /**
     * 给角色分配资源
     */
    @PostMapping("/allocResource")
    public Result<String> allocResource(RoleResourceDto roleResourceDto) {
        Long roleId = roleResourceDto.getRoleId();
        List<Long> resourceIds = roleResourceDto.getResourceIds();
        //删除该角色的相关资源
        LambdaQueryWrapper<UmsRoleResourceRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRoleResourceRelation::getResourceId,roleId);
        roleResourceRelationService.remove(lqw);
        //想角色资源表中添加数据
        List<UmsRoleResourceRelation> roleResourceRelations = resourceIds.stream().map(resourceId -> {
            UmsRoleResourceRelation roleResourceRelation = new UmsRoleResourceRelation();
            roleResourceRelation.setRoleId(roleId);
            roleResourceRelation.setResourceId(resourceId);
            return roleResourceRelation;
        }).collect(Collectors.toList());
        //批量添加
        roleResourceRelationService.saveBatch(roleResourceRelations);
        return Result.success();
    }

}
